﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using HtmlExtractor;
using System.Runtime.Serialization;
using System.IO;

namespace Reader.View
{
    public class OnlineObjectView:UserControl
    {
        #region object
        protected virtual object GenerateObject(string html, string uri) 
        {
            throw new NotImplementedException();
        }  
        public void LoadObject(string uri,Type type)
        {
            object obj = null;
            string path = null;
            if (Cache.Current.TryGet(uri, out obj))
            {
                SetElement(obj);
            }
            else if (ReaderConfig.IsUseLoaclBook && ReaderPath.TryGetSiteFileName(uri, out path))
            {
               // object result = null;
                DataContractSerializer serializer = new DataContractSerializer(type);
                try
                {
                    if (File.Exists(path))
                    {
                        obj = serializer.ReadObject(File.OpenRead(path));
                        Cache.Current.Add(uri, obj,ReaderConfig.MinCacheTime);
                        SetElement(obj);
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
               
            }
            else
            {
                WebClient client = new WebClient();
                client.Encoding = new Gb2312Encoding();
                client.DownloadStringCompleted += (s, args) =>
                {
                    if (args.Error == null)
                    {   
                        obj = GenerateObject(args.Result, uri);
                        Cache.Current.Add(uri, obj,ReaderConfig.MinCacheTime);
                        SetElement(obj);
                    }
                };
                client.DownloadStringAsync(new Uri(uri));
            }

        }
        protected virtual void SetElement(object rdoc) { }
        #endregion
    }
}
